package com.asset.dispoal.file.evidenceRecognition.service.commom;

import com.asset.dispoal.file.evidenceRecognition.domain.db.entity.EvidenceTypeFileDo;
import com.asset.dispoal.file.evidenceRecognition.domain.db.mapper.EvidenceRecognitionMapper;
import com.asset.dispoal.file.evidenceRecognition.dto.DownloadAndDelEvidenceRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.compress.DynamicFile;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.io.IOUtil;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.core.util.ZipUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.io.File;
import java.io.OutputStream;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class DownloadAndDelEvidenceCommand implements BaseCommand<DownloadAndDelEvidenceRequest, Result> {

    @Autowired
    private Environment environment;

    @Autowired
    private BaseIdeable<String> ideable;
    @Autowired
    EvidenceRecognitionMapper evidenceRecognitionMapper;

    @Override
    public Result<String> execute(DownloadAndDelEvidenceRequest request) {
        List<EvidenceTypeFileDo> evidenceTypeFileDoList;
        if (StringUtil.equals(request.getType(), "1")) {
            evidenceTypeFileDoList = evidenceRecognitionMapper.queryNotMatchByEvidenceType(request.getAssetInstBatchId(), request.getTypeValue());
        } else {
            evidenceTypeFileDoList = evidenceRecognitionMapper.queryNotMatchByRecordId(request.getAssetInstBatchId(), request.getTypeValue());
        }
        if (CollectionUtil.isEmpty(evidenceTypeFileDoList)) {
            return Result.faild("暂无未匹配到的证据");
        }
        for (EvidenceTypeFileDo fileDo : evidenceTypeFileDoList) {
            evidenceRecognitionMapper.deleteByEvidenceId(fileDo.getEvidenceId());
        }
        OutputStream os = null;
        String basePath;
        try {
            String docUrl = environment.getProperty("file.evidence.url");
            LocalDate now = LocalDate.now();
            String year = String.valueOf(now.getYear());
            String month = String.valueOf(now.getMonthValue());
            String day = String.valueOf(now.getDayOfMonth());

            basePath = "/custdownload/" + year + "/" + month + "/" + day + "/" + ideable.generateId() + ".zip";
            File file = new File(docUrl + basePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            os = Files.newOutputStream(file.toPath());
            List<DynamicFile> zipDynamicFileDTOList = new ArrayList<>();
            Map<String, List<EvidenceTypeFileDo>> evidenceTypeFileDoMap = evidenceTypeFileDoList.stream().collect(Collectors.groupingBy(EvidenceTypeFileDo::getEvidenceTypeName));
            evidenceTypeFileDoMap.forEach((typeName, evidenceTypeFileDos) -> {
                List<File> files = new ArrayList<>();
                evidenceTypeFileDos.forEach(evidenceTypeFileDo -> files.add(new File(docUrl + evidenceTypeFileDo.getFilename())));
                DynamicFile zipDynamicFileDTO = new DynamicFile();
                zipDynamicFileDTO.setDirName(typeName);
                zipDynamicFileDTO.setFileList(files);
                zipDynamicFileDTOList.add(zipDynamicFileDTO);
            });
            ZipUtil.toDynamicZip(zipDynamicFileDTOList, os);
            return Result.ok(basePath);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(500, e.getMessage());
        } finally {
            IOUtil.close(os);
        }
    }
}
